import os

from sc_engine.apps import messages as msgs
from sc_engine.repositories import Repository, use
from sc_engine.repositories.stores import PickleFileStore

from sc_engine.apps.data.league_stage.converter import LeagueStageConverter

def make_app(app_name, root_config, config):
    data_directory = root_config['data_directory']

    store_filename = os.path.join(data_directory, app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = LeagueStageDataApp(repo)

    return {
        msgs.LeagueDataTemplateAnnouncement : app.league_data_template_announcement,
        msgs.LeagueStagePathDateRequested : app.league_stage_path_date_requested,
    }

class LeagueStageDataApp(object):
    """Compute information regarding a league's various stages
    
    Will create and update data on the stages of a league based on combining
    it's knowledge of the league's stages with the information received from
    when a league stage was found to have been played.
    """
    def __init__(self, repo):
        self.repo = repo

    @use('repo', 'leagues')
    def league_data_template_announcement(self, msg, leagues):
        leagues[msg.name_key] = LeagueStageConverter(msg.stage_template,
            msg.stage_known_dates, msg.stage_aliases, msg.stage_exceptions)

        return msgs.LeagueDataAnnouncement(msg.name_key, msg.name, msg.alias)
    
    @use('repo', 'leagues', 'league_stages')
    def league_stage_path_date_requested(self, msg, leagues, league_stages):
        out = []

        league_converter = leagues[msg.league]
        stage_path = league_converter.find_stage_path(msg.stage, msg.date)

        out.append(msgs.LeagueStagePathDateAnnouncement(msg.league,
            stage_path, msg.date))

        stage_data = league_converter.find_stage_data(stage_path)

        stages = league_stages.setdefault(msg.league, {})

        for data in stage_data:
            stage_path_tupled = tuple(data['stage_path'])
            if stage_path_tupled not in stages:
                stages[stage_path_tupled] = set()
            stages[stage_path_tupled].add(msg.date)

            all_dates = list(stages[stage_path_tupled])
            all_dates.sort()
            data['start_date'] = all_dates[0]
            data['end_date'] = all_dates[-1]
            out.append(msgs.LeagueStageDataAnnouncement(msg.league, **data))

        return out

